package com.zim.ta_service.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 常用方法工具类
 */
public class CommUtil {

	private static final String CRON_EXPRESSION_SECONDS = "0/{} * * * * ?";
	private static final String CRON_EXPRESSION_MINUTES = "0 0/{} * * * ?";
	private static final String CRON_EXPRESSION_HOURS   = "0 0 0/{} * * ?";

	/**
	 * 获取当天最早时间
	 * @param date
	 * @return XXXX-XX-XX 00:00:00
	 */
	public static Date getDateMin(Date date) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
		LocalDateTime beginDateTime = localDateTime.with(LocalTime.MIN);
		return Date.from(beginDateTime.atZone(ZoneId.systemDefault()).toInstant());
	}

	/**
	 * 获取当天最晚时间
	 * @param date
	 * @return XXXX-XX-XX 23:59:59
	 */
	public static Date getDateMax(Date date) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
		LocalDateTime beginDateTime = localDateTime.with(LocalTime.MAX);
		return Date.from(beginDateTime.atZone(ZoneId.systemDefault()).toInstant());
	}

	/**
	 * 获取两个日期之间 N等分的小时差，向上取整 不足1H 按1H算
	 * @param dateFrom
	 * @param dateTo
	 * @param splitCount
	 * @return
	 */
	public static int getHoursBetweenDate(Date  dateFrom, Date dateTo, int splitCount){
		long time = dateTo.getTime() - dateFrom.getTime();
		long countHours = time/(60*60*1000); // 转换成小时
		Double hourCount = Double.valueOf(Math.ceil((countHours/Double.valueOf(splitCount))));
		return hourCount > 1 ? hourCount.intValue() : 1;
	}

	/**
	 * 根据秒数转换为Cron表达式
	 * @param seconds 秒数
	 * @return cron
	 */
	public static String cronBySeconds(Integer seconds) {
		if (null == seconds) {
			// 默认1分钟
			return "0 * * * * ?";
		}
		if (seconds >= 3600) {
			// 小时
			return StrUtil.format(CRON_EXPRESSION_HOURS, seconds / 3600);
		}

		if (seconds >= 60) {
			// 分钟
			return StrUtil.format(CRON_EXPRESSION_MINUTES, seconds / 60);
		}
		// 秒
		return StrUtil.format(CRON_EXPRESSION_SECONDS, seconds);
	}

	public static List<Date> getMinutesRangeByInterval(Date from, Date to, Integer interval) {
		List<Date> list = new ArrayList<>();

		Date beginTime = DateUtil.beginOfMinute(from);
		while (beginTime.compareTo(to) <= 0) {
			list.add(beginTime);
			beginTime = DateUtil.offsetMinute(beginTime, 1);
		}
		return list;
	}

	public static <T> List<T> checkListReSelf(List<T> collection){
		return CollUtil.isNotEmpty(collection) ? collection : null;
	}

}
